package org.sun.web.controller;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.inject.Inject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.sun.basic.model.SysUser;
import org.sun.basic.service.IUserService;
import org.sun.web.util.AppUtil;
import org.sun.web.util.DataUtil;
import org.sun.web.util.MD5Util;
import org.sun.web.util.UUIDUtil;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.util.JsonParserDelegate;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
public class LoginController {
	
	private final Logger logger=LoggerFactory.getLogger(getClass());
	
	@Inject
	private IUserService userService;
	
	@Inject
	private Producer captchaProducer;
	
	

	@RequestMapping(value={"/login"})
	public String login(@RequestParam(value="error",required=false) boolean error,Model model){
		
		if (error == true) {  
			logger.debug("---------登录失败，登录用户不正确！------");
            // Assign an error message  
			model.addAttribute("error", "您的用户名或密码不正确！");
        } 
		return "login/login";
	}
	@RequestMapping(value={"/index/index"},method=RequestMethod.GET)
	public String index(){
		Object principal=SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		if(principal instanceof UserDetails){
			String username=((UserDetails)principal).getUsername();
			System.out.println("---------"+username+"-------------");
		}else{
			System.out.println("---------"+principal.toString()+"-------------");
		}
		return "index/index";
	}
	@RequestMapping(value="/register",method=RequestMethod.GET)
	public String register(){
		return "login/register";
	}
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String register(SysUser user,Model model,HttpServletRequest request){
		user.setId(UUIDUtil.getUUID());
		String pwd=MD5Util.md5(user.getName(), user.getPassword());
		user.setStatus(1);
		user.setPassword(pwd);
		SimpleDateFormat sdf=new SimpleDateFormat("YYYYMMdd");
		user.setCreatedate(sdf.format(new Date()).toString());
		user.setAppid(AppUtil.getAppId());
		userService.add(user);
		return "login/login";
	}
	@RequestMapping(value="/denied",method=RequestMethod.GET)
	public String auth(){
		logger.debug("-------denied-------");
		return "redirect:/login";
	}
	
	@RequestMapping(value="/logout",method=RequestMethod.GET)
	public String exit(){
		logger.debug("-------exit-------");
		return "redirect:/login";
	}
	
	/**
	 * 检验验证码是否正确
	 * @param abc
	 * @return
	 */
	@RequestMapping(value="checkCode",method=RequestMethod.POST)
	public @ResponseBody String  getData(@RequestBody String code,
			HttpServletRequest request,
			HttpServletResponse response){
		HttpSession session = request.getSession();
		String ctrCode = (String) session
				.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		String resultCode = "1";
		if (null != code && ctrCode.equalsIgnoreCase(code)) {
			resultCode = "0";
		}
		return resultCode;
	}
	/**
	 * @summary 验证码生成方法
	 * @param request
	 * @param response
	 * @return null
	 * @throws Exception
	 * @detail
	 */
	@RequestMapping(value = "kaptchaImage")
	public ModelAndView getKaptchaImage(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();
		// String code = "";
		// session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
		// code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		// System.out.println("******************验证码1是: " + code +
		// "******************");
		response.setDateHeader("Expires", 0);
		// Set standard HTTP/1.1 no-cache headers.
		response.setHeader("Cache-Control",
				"no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		response.setHeader("Pragma", "no-cache");
		// return a jpeg
		response.setContentType("image/jpeg");
		// create the text for the image
		String capText = captchaProducer.createText();
		// store the text in the session
		session.setAttribute(Constants.KAPTCHA_SESSION_KEY, capText);
		// code = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
		// System.out.println("******************验证码2是: " + code +
		// "******************");
		// create the image with the text
		BufferedImage bi = captchaProducer.createImage(capText);
		ServletOutputStream out = response.getOutputStream();
		// write the data out
		ImageIO.write(bi, "jpg", out);
		try {
			out.flush();
		} finally {
			out.close();
		}
		return null;
	}
	@RequestMapping(value="upload")
	public @ResponseBody String  fileUpload(DefaultMultipartHttpServletRequest request,HttpServletResponse response){
		BufferedInputStream bis=null;
		StringBuilder sb=new StringBuilder();
		try {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			 MultipartFile multipartFile = multipartRequest.getFile("fileupload"); 
			bis=new BufferedInputStream(multipartFile.getInputStream());
			byte[] b=new byte[30];
			while((bis.read(b))>0){
				sb.append(new String(b));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				if(bis!=null)bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
